package ru.tulupov.collectionsbenchmark;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ru.tulupov.collectionsbenchmark.model.Car;
import ru.tulupov.collectionsbenchmark.util.CSVParser;
import ru.tulupov.collectionsbenchmark.util.CarBuilder;

public class Data {
	private static final Logger LOGGER = Logger.getLogger(Data.class);
	private static final String FILE = "csv.txt";

	private static class DataHolder {
		public static Data INSTANCE = new Data();
	}

	public static Data getInstance() {
		return DataHolder.INSTANCE;
	}

	private Car[] array;

	private Data() {
		InputStream is = null;
		try {
			LOGGER.info("Starts loading file.");
			is = new FileInputStream(FILE);
			CSVParser parser = new CSVParser(is);
			List<String[]> list = parser.parse();
			CarBuilder builder = new CarBuilder();
			List<Car> cars = new ArrayList<Car>();
			for (String[] data : list) {
				try {
					cars.add(builder.build(data));
				} catch (IllegalArgumentException e) {
					LOGGER.error("An error has occurred", e);
				}
			}

			array = new Car[cars.size()];
			cars.toArray(array);
			LOGGER.info("File loaded.");

		} catch (FileNotFoundException e) {

		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					LOGGER.error("An error has occurred", e);
				}
			}
		}
	}

	public Car[] getCars() {
		return array;
	}
}
